package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;
import webservices.LoginShareService;

/**
 * Rappresenta la servlet principale della web application.
 * @author Rachid Ouchary, Fabio Strocco, Max Passaghe, Marco Tansini.
 */
public class MainDispatcher extends HttpServlet {

    @Resource(name = "jms/coda")
    private Queue coda;
    @Resource(name = "jms/codaFactory")
    private ConnectionFactory codaFactory;
    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/LoginShareService/LoginShare.wsdl")
    private LoginShareService service;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String operation = request.getParameter("operation");

        if (operation == null) {
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else if (operation.equals("login")) {
            webservices.LoginShare port = service.getLoginSharePort();
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            webservices.Utente result = port.carica(username, password);
            if(result != null) {
                session.setAttribute("username", username);
            }


            username = request.getParameter("username");
            // TODO process result here
            List<webservices.Wish> wishList = (result != null
                    ? port.getOrderedUserWishList(username)
                    : null);
            request.setAttribute("wishList", wishList);
            request.getRequestDispatcher("ws_wishlist.jsp").forward(request, response);
        } else if (operation.equals("remove_wish") &&
                   session.getAttribute("username") != null ) {
            try {
                sendJMSMessageToCoda(request.getParameter("wish_id"));

                webservices.LoginShare port = service.getLoginSharePort();
                String username = (String) session.getAttribute("username");

                List<webservices.Wish> wishList =  port.getOrderedUserWishList(username);
                request.setAttribute("wishList", wishList);
                request.getRequestDispatcher("ws_wishlist.jsp").forward(request, response);
            } catch (JMSException ex) {
                Logger.getLogger(MainDispatcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";

    }// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="JMS calls.">
    private Message createJMSMessageForjmsCoda(Session session, Object messageData) throws JMSException {
        // TODO create and populate message to send
        TextMessage tm = session.createTextMessage();
        tm.setText(messageData.toString());
        return tm;
    }

    private void sendJMSMessageToCoda(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = codaFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(coda);
            messageProducer.send(createJMSMessageForjmsCoda(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
    // </editor-fold>
}
